<template>
  <div class="survey-page">
    <div class="survey-container">
      <!-- 问卷标题区域 -->
      <div class="survey-header">
        <h1 class="survey-title">{{ survey.title }}</h1>
        <p class="survey-description" v-if="survey.description">{{ survey.description }}</p>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="survey-loading">
        <div class="loading-spinner"></div>
        <p>正在加载问卷...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="survey-error">
        <div class="error-icon">!</div>
        <h2>加载失败</h2>
        <p>{{ errorMessage }}</p>
        <button class="btn primary-btn" @click="fetchSurvey">重新加载</button>
      </div>

      <!-- 提交成功状态 -->
      <div v-else-if="submitted" class="survey-success">
        <div class="success-icon">✓</div>
        <h2>提交成功</h2>
        <p>感谢您的参与！</p>
        <button class="btn" @click="goBack">返回首页</button>
      </div>

      <!-- 问卷已结束状态 -->
      <div v-else-if="survey.status === 'ended'" class="survey-message">
        <h2>问卷已结束</h2>
        <p>该问卷已停止收集回答</p>
        <button class="btn" @click="goBack">返回首页</button>
      </div>

      <!-- 问卷未发布状态 -->
      <div v-else-if="survey.status === 'draft'" class="survey-message">
        <h2>问卷未发布</h2>
        <p>该问卷尚未发布，无法填写</p>
        <button class="btn" @click="goBack">返回首页</button>
      </div>

      <!-- 问卷内容 -->
      <form v-else class="survey-form" @submit.prevent="submitSurvey">
        <!-- 进度指示器 -->
        <div class="progress-bar">
          <div class="progress-fill" :style="{width: `${calculateProgress()}%`}"></div>
          <span class="progress-text">{{ calculateProgress() }}% 完成</span>
        </div>

        <!-- 问题列表 -->
        <div class="questions-list">
          <div v-for="(question, qIndex) in survey.questions" :key="qIndex" class="question-card">
            <!-- 问题标题 -->
            <div class="question-header">
              <span class="question-number">{{ qIndex + 1 }}</span>
              <div class="question-info">
                <h3 class="question-title">{{ question.title || question.content || question.question_content || '无标题问题' }}</h3>
                <div class="question-tags">
                  <span v-if="false" class="question-type">{{ getQuestionTypeName(question.type) }}</span>
                  <span v-if="question.required" class="required-tag">必答</span>
                </div>
              </div>
            </div>
            
            <!-- 问题描述 -->
            <p v-if="question.description" class="question-description">{{ question.description }}</p>
            
            <!-- 单选题 -->
            <div v-if="question.type === 'radio'" class="options-container">
              <div v-if="!question.options || question.options.length === 0" class="no-options">
                该问题没有选项
              </div>
              <label 
                v-else
                v-for="(option, oIndex) in question.options" 
                :key="oIndex" 
                class="option-item" 
                :class="{'selected': answerForm.answers[qIndex].selected_options[0] === option.value}"
              >
                <input 
                  type="radio" 
                  :name="`question_${qIndex}`" 
                  :value="option.value"
                  v-model="answerForm.answers[qIndex].selected_options[0]"
                  class="radio-input"
                >
                <span class="custom-radio"></span>
                <span class="option-text">{{ option.label }}</span>
              </label>
            </div>
            
            <!-- 多选题 -->
            <div v-else-if="question.type === 'checkbox'" class="options-container">
              <div v-if="!question.options || question.options.length === 0" class="no-options">
                该问题没有选项
              </div>
              <label 
                v-else
                v-for="(option, oIndex) in question.options" 
                :key="oIndex" 
                class="option-item"
                :class="{'selected': answerForm.answers[qIndex].selected_options.includes(option.value)}"
              >
                <input 
                  type="checkbox" 
                  :value="option.value"
                  v-model="answerForm.answers[qIndex].selected_options"
                  class="checkbox-input"
                >
                <span class="custom-checkbox"></span>
                <span class="option-text">{{ option.label }}</span>
              </label>
            </div>
            
            <!-- 下拉选择 -->
            <div v-else-if="question.type === 'select'" class="select-container">
              <div v-if="!question.options || question.options.length === 0" class="no-options">
                该问题没有选项
              </div>
              <select v-else v-model="answerForm.answers[qIndex].selected_options[0]" class="select-input">
                <option value="" disabled>请选择...</option>
                <option v-for="(option, oIndex) in question.options" :key="oIndex" :value="option.value">
                  {{ option.label }}
                </option>
              </select>
            </div>
            
            <!-- 文本输入 -->
            <div v-else-if="question.type === 'text'" class="text-container">
              <textarea 
                v-model="answerForm.answers[qIndex].content" 
                rows="4" 
                placeholder="请在此输入您的回答..."
                class="text-input"
              ></textarea>
            </div>
            
            <!-- 评分 -->
            <div v-else-if="question.type === 'rate'" class="rate-container">
              <div class="rate-options">
                <button 
                  v-for="n in (question.max || 5)" 
                  :key="n" 
                  type="button"
                  class="rate-button" 
                  :class="{'active': Number(answerForm.answers[qIndex].content) >= n}"
                  @click="answerForm.answers[qIndex].content = n"
                >
                  {{ n }}
                </button>
              </div>
              <div class="rate-labels">
                <span>不满意</span>
                <span>非常满意</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 提交区域 -->
        <div class="form-actions">
          <p class="required-notice"><span class="required-symbol">*</span> 表示必答题</p>
          <button type="submit" class="submit-btn" :disabled="submitting">
            {{ submitting ? '提交中...' : '提交问卷' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const surveyId = route.params.id

// 响应式数据
const survey = ref({
  title: '',
  description: '',
  questions: [],
  status: ''
})
const loading = ref(true)
const error = ref(false)
const errorMessage = ref('')
const submitted = ref(false)
const submitting = ref(false)

// 创建axios实例
const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 5000
})

// 初始化答案表单
const answerForm = reactive({
  survey_id: surveyId,
  answers: []
})

// 计算完成进度
const calculateProgress = () => {
  if (!survey.value.questions || !survey.value.questions.length) return 0
  
  const totalQuestions = survey.value.questions.length
  let answeredQuestions = 0
  
  answerForm.answers.forEach((answer, index) => {
    const question = survey.value.questions[index]
    if (
      (question.type === 'text' && answer.content.trim() !== '') ||
      (question.type === 'rate' && answer.content !== '') ||
      (question.type === 'checkbox' && answer.selected_options.length > 0) ||
      (question.type === 'radio' && answer.selected_options[0]) ||
      (question.type === 'select' && answer.selected_options[0])
    ) {
      answeredQuestions++
    }
  })
  
  return Math.round((answeredQuestions / totalQuestions) * 100)
}

// 获取问题类型名称
const getQuestionTypeName = (type) => {
  const types = {
    'radio': '单选题',
    'checkbox': '多选题',
    'select': '下拉选择',
    'text': '文本题',
    'rate': '评分题'
  }
  return types[type] || '未知类型'
}

// 获取问卷数据
const fetchSurvey = async () => {
  loading.value = true
  error.value = false
  
  try {
    const res = await instance.get(`/api/surveys/${surveyId}`)
    survey.value = res.data.data
    
    // 数据适配和处理
    survey.value.questions = survey.value.questions.map(question => {
      // 标题处理
      if (!question.title && (question.content || question.question_content)) {
        question.title = question.content || question.question_content
      }
      
      // 类型映射 - 将后端类型映射到前端类型
      const typeMapping = {
        'single': 'radio',
        'multiple': 'checkbox',
        'text': 'text',
        'rating': 'rate'
      }
      
      // 如果question.type是后端类型，则转换为前端类型
      if (typeMapping[question.type]) {
        question.type = typeMapping[question.type]
      }
      
      // 确保选项格式正确 - 适配不同的后端数据结构
      if (['radio', 'checkbox', 'select'].includes(question.type)) {
        // 如果选项不存在或不是数组，初始化为空数组
        if (!question.options || !Array.isArray(question.options)) {
          // 尝试从其他可能的字段获取选项
          let options = []
          
          // 情况1: 选项可能存在于question.data.options
          if (question.data && Array.isArray(question.data.options)) {
            options = question.data.options
          }
          // 情况2: 选项可能存在于question.choices
          else if (Array.isArray(question.choices)) {
            options = question.choices.map(choice => ({
              value: choice.value || choice.id || choice,
              label: choice.label || choice.text || choice
            }))
          }
          // 情况3: 选项可能是一个普通对象
          else if (question.options && typeof question.options === 'object') {
            options = Object.entries(question.options).map(([key, value]) => ({
              value: key,
              label: value
            }))
          }
          
          question.options = options
        } else {
          // 确保每个选项都有value和label属性
          question.options = question.options.map(option => {
            if (typeof option === 'string') {
              return { value: option, label: option }
            } else if (typeof option === 'object') {
              return {
                value: option.value || option.id || option.content || '',
                label: option.label || option.text || option.content || option.value || ''
              }
            }
            return option
          })
        }
      }
      
      return question
    })
    
    console.log('处理后的问卷数据:', survey.value)
    
    // 初始化答案数组
    answerForm.answers = survey.value.questions.map(question => {
      if (question.type === 'checkbox') {
        return { question_id: question.id, content: '', selected_options: [] }
      } else if (question.type === 'text' || question.type === 'rate') {
        return { question_id: question.id, content: '', selected_options: [] }
      } else {
        return { question_id: question.id, content: '', selected_options: [''] }
      }
    })
    
  } catch (err) {
    console.error('获取问卷失败:', err)
    error.value = true
    errorMessage.value = err.response?.data?.message || '获取问卷数据失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

// 提交问卷
const submitSurvey = async () => {
  // 验证必填题是否已填写
  for (let i = 0; i < survey.value.questions.length; i++) {
    const question = survey.value.questions[i]
    const answer = answerForm.answers[i]
    
    if (question.required) {
      if (question.type === 'text' || question.type === 'rate') {
        if (!answer.content && answer.content !== 0) {
          alert(`第${i + 1}题是必填题，请填写完整`)
          return
        }
      } else {
        if (Array.isArray(answer.selected_options) && 
            (answer.selected_options.length === 0 || 
             (answer.selected_options.length === 1 && !answer.selected_options[0]))) {
          alert(`第${i + 1}题是必填题，请填写完整`)
          return
        }
      }
    }
  }
  
  // 确保文本和评分题的content是字符串类型
  for (let i = 0; i < survey.value.questions.length; i++) {
    const question = survey.value.questions[i]
    const answer = answerForm.answers[i]
    
    if (question.type === 'text' || question.type === 'rate') {
      if (typeof answer.content !== 'string') {
        answer.content = answer.content?.toString() || ''
      }
    }
  }
  
  submitting.value = true
  
  try {
    await instance.post('/api/responses/submit', answerForm)
    submitted.value = true
  } catch (err) {
    console.error('提交问卷失败:', err)
    alert(err.response?.data?.message || '提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 返回按钮
const goBack = () => {
  router.push('/')
}

// 页面加载时获取问卷数据
onMounted(() => {
  fetchSurvey()
})
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 应用根元素样式 */
:global(#app) {
  margin: 0 auto;
  width: 100%;
  max-width: 100%;
}

/* 页面容器样式 */
.survey-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  padding: 30px 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 问卷容器 */
.survey-container {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 问卷标题区域 */
.survey-header {
  padding: 30px;
  background: linear-gradient(135deg, #4a6cf7, #6a8ff8);
  color: white;
  text-align: center;
}

.survey-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
}

.survey-description {
  font-size: 16px;
  opacity: 0.9;
  line-height: 1.5;
}

/* 加载状态 */
.survey-loading {
  padding: 60px 0;
  text-align: center;
}


.loading-spinner {
  display: inline-block;
  width: 50px;
  height: 50px;
  border: 4px solid rgba(74, 108, 247, 0.2);
  border-radius: 50%;
  border-top-color: #4a6cf7;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 错误状态 */
.survey-error {
  padding: 60px 30px;
  text-align: center;
}

.error-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background-color: #fef1f1;
  color: #e53935;
  border-radius: 50%;
  font-size: 30px;
  margin-bottom: 20px;
  font-weight: bold;
}

/* 成功状态 */
.survey-success {
  padding: 60px 30px;
  text-align: center;
}

.success-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 60px;
  height: 60px;
  background-color: #edf7ed;
  color: #4caf50;
  border-radius: 50%;
  font-size: 30px;
  margin-bottom: 20px;
}

/* 问卷消息状态 */
.survey-message {
  padding: 60px 30px;
  text-align: center;
}

/* 表单样式 */
.survey-form {
  padding: 30px;
}

/* 进度条 */
.progress-bar {
  height: 8px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin-bottom: 30px;
  position: relative;
}

.progress-fill {
  height: 100%;
  background-color: #4a6cf7;
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  right: 0;
  top: -20px;
  font-size: 14px;
  color: #4a6cf7;
}

/* 问题卡片 */
.question-card {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 问题标题 */
.question-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.question-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background-color: #4a6cf7;
  color: white;
  border-radius: 50%;
  margin-right: 5px;
  font-size: 14px;
  flex-shrink: 0;
}

/* .question-info {
  flex: 1;
} */

.question-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.4;
  color: #333;
}

.question-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;
}

.question-type {
  display: inline-block;
  padding: 2px 8px;
  background-color: #e3f2fd;
  color: #2196f3;
  border-radius: 50px;
  font-size: 12px;
  margin-right: 10px;
}

.question-content {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-right: 10px;
  flex: 1;
}

.required-tag {
  display: inline-block;
  padding: 2px 8px;
  background-color: #ffebee;
  color: #f44336;
  border-radius: 50px;
  font-size: 12px;
}

.question-description {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 15px;
  margin-left: 40px;
}

/* 选项容器 */
.options-container {
  margin-left: 40px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 单选/多选样式 */
.option-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.option-item:hover {
  background-color: #f8f9fa;
}

.option-item.selected {
  background-color: #f0f7ff;
  border-color: #4a6cf7;
}

.radio-input, .checkbox-input {
  position: absolute;
  opacity: 0;
}

.custom-radio, .custom-checkbox {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 10px;
  background-color: #fff;
  border: 2px solid #ced4da;
  position: relative;
}

.custom-radio {
  border-radius: 50%;
}

.custom-checkbox {
  border-radius: 4px;
}

.option-item.selected .custom-radio::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 10px;
  height: 10px;
  background-color: #4a6cf7;
  border-radius: 50%;
}

.option-item.selected .custom-checkbox::after {
  content: '';
  position: absolute;
  top: 2px;
  left: 6px;
  width: 5px;
  height: 10px;
  border: solid #4a6cf7;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

.option-text {
  font-size: 14px;
}

/* 下拉选择 */
.select-container {
  margin-left: 40px;
}

.select-input {
  width: 100%;
  padding: 10px 15px;
  font-size: 14px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  appearance: none;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%234a6cf7' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14L2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: right 15px center;
  background-size: 12px;
}

.select-input:focus {
  border-color: #4a6cf7;
  outline: none;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
}

/* 文本输入 */
.text-container {
  margin-left: 40px;
}

.text-input {
  width: 100%;
  padding: 12px 15px;
  font-size: 14px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  resize: vertical;
  min-height: 100px;
  transition: border-color 0.2s;
  font-family: inherit;
}

.text-input:focus {
  border-color: #4a6cf7;
  outline: none;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
}

/* 评分 */
.rate-container {
  margin-left: 40px;
}

.rate-options {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

.rate-button {
  width: 40px;
  height: 40px;
  border: 1px solid #ced4da;
  background-color: #fff;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s;
}

.rate-button:hover {
  border-color: #4a6cf7;
}

.rate-button.active {
  background-color: #4a6cf7;
  color: white;
  border-color: #4a6cf7;
}

.rate-labels {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #6c757d;
}

/* 提交区域 */
.form-actions {
  margin-top: 40px;
  text-align: center;
}

.required-notice {
  margin-bottom: 15px;
  font-size: 14px;
  color: #6c757d;
}

.required-symbol {
  color: #f44336;
  font-size: 16px;
}

.submit-btn {
  background-color: #4a6cf7;
  color: white;
  border: none;
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-btn:hover {
  background-color: #3a5be6;
}

.submit-btn:disabled {
  background-color: #a0b6fa;
  cursor: not-allowed;
}

/* 通用按钮 */
.btn {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
  color: #495057;
  padding: 10px 20px;
  font-size: 14px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn:hover {
  background-color: #e9ecef;
}

.primary-btn {
  background-color: #4a6cf7;
  border-color: #4a6cf7;
  color: white;
}

.primary-btn:hover {
  background-color: #3a5be6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .survey-container {
    border-radius: 0;
  }
  
  .survey-header {
    padding: 20px;
  }
  
  .survey-form {
    padding: 20px;
  }
  
  .question-description,
  .options-container,
  .select-container,
  .text-container,
  .rate-container {
    margin-left: 20px;
  }
  
  .submit-btn {
    width: 100%;
  }
}

.no-options {
  padding: 10px;
  color: #e53935;
  background-color: #ffebee;
  border-radius: 6px;
  font-size: 14px;
  text-align: center;
}
</style>
